<?php
/**
 * Crc CMS
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage Water Type
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @author     Jipa Ciprian <ciprian.jipa@yahoo.com>
 * @copyright  Copyright (c) 2012
 * @version    $Id: adminController.php 54 2012-10-02 15:41:20Z mcalin45@gmail.com $
 */

/**
 * User admin controller
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage Water Type
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @author     Jipa Ciprian <ciprian.jipa@yahoo.com>
 * @copyright  Copyright (c) 2012
 */
class Watertype_AdminController extends Zend_Controller_Action
{
    /**
     * @var Bisna\Application\Container\DoctrineContainer
     */
    protected $doctrine;

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * @var Crc\Entity\RepositoryWaterTypeRepository
     */
    protected $waterTypeRepository;

    public function init()
    {
        $this->doctrine = Zend_Registry::get('doctrine');
        $this->entityManager = $this->doctrine->getEntityManager();
        $this->waterTypeRepository = $this->entityManager->getRepository('\Crc\Entity\WaterType');
    }

    /**
     * Display user list
     *
     * @return void
     */
    public function indexAction()
    {
        $sessionGrid = new Zend_Session_Namespace(
            'Grid_' .
            $this->getRequest()->getModuleName() . '_' .
            $this->getRequest()->getControllerName() . '_' .
            $this->getRequest()->getActionName()
        );

        if ($this->_getParam('do_filter') == 1) {
            if ($this->_getParam('reset_filter') == 2) {
                unset($sessionGrid->filters);
            } else {
                $sessionGrid->filters = $this->_getParam('filter');
            }
            $this->_redirect('/watertype/admin');
        }
        if ($this->_getParam('set')) {
            switch ($this->_getParam('set')) {
                case 'order':
                    $order['type'] = ($sessionGrid->order['field'] == $this->_getParam('field') && $sessionGrid->order['type'] == 'ASC') ? 'DESC' : 'ASC';
                    $order['field'] = $this->_getParam('field');
                    $sessionGrid->order = $order;
                    break;

                default:
                    # code...
                    break;
            }

            $this->_redirect('/watertype/admin');
        }

        //$waterTypes = new Application_Model_Collection_WaterType();
        //$waterTypes = $this->waterTypeRepository->findBy(array(), null, 2);
        //echo'<pre>';Doctrine\Common\Util\Debug::dump($waterTypes);exit;
         $sessionGrid->order;
        $queryBuilder = $this->entityManager->createQueryBuilder();
        $options = array(
            'where' => array(
                'status >= ?' => Crc\Entity\WaterType::STATUS_INACTIVE
            ),
            'order' => ($sessionGrid->order['field']) ? array($sessionGrid->order['field'] , $sessionGrid->order['type']) : array('sortOrder' , 'ASC')
        );


        $queryBuilder->select('wt')
             ->from('Crc\Entity\WaterType', 'wt')
             ->orderBy("wt." . $options['order'][0], $options['order'][1])
             ->where('wt.status>=?1')
             ->setParameter(1, Crc\Entity\WaterType::STATUS_INACTIVE);

             if (is_array($sessionGrid->filters['fields']) && count($sessionGrid->filters['fields']) > 0) {
                         foreach($sessionGrid->filters['fields'] as $field) {
                             switch($sessionGrid->filters['type'][$field]) {
                                 case 'text':
                                     switch($sessionGrid->filters['operators'][$field]) {
                                         case '~' :
                                             $queryBuilder->andWhere(
                                                    $queryBuilder->expr()->like('wt.' . $field, '?2'))
                                                    ->setParameter(2, '%'.$sessionGrid->filters['values'][$field].'%');
                                             break;
                            case '!~' :
                                $queryBuilder->andWhere('wt.' . $field . ' NOT LIKE ?2')
                                             ->setParameter(2, '%'.$sessionGrid->filters['values'][$field].'%');

                                break;
                        }
                        break;

                    case 'arr':
                        switch($sessionGrid->filters['operators'][$field]) {
                            case '=' :
                                $queryBuilder->andWhere('wt.' . $field . '  IN (?3)')
                                             ->setParameter(3, $sessionGrid->filters['values'][$field]);


                                break;

                            case '!' :
                                 $queryBuilder->andWhere('wt.' . $field . '  NOT IN (?3)')
                                              ->setParameter(3, $sessionGrid->filters['values'][$field]);


                                break;
                        }
                        break;
                }
            }
        }



        //$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
        $adapter = new Crc_Paginator_Adapter_Doctrine($queryBuilder);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam('page'));
        $paginator->setItemCountPerPage(10);
        $this->view->paginator = $paginator;

        //Zend_Debug::dump($paginator);
        //$this->view->itemsList = $waterTypes->fetchAll($waterTypes->select()->where('status >= ?' , '0'));
        //exit;
    }

    /**
     * Edit a water type
     *
     * @return void
     */
    public function saveAction()
    {
        $itemId = $this->getRequest()->getParam('id');
        if ($itemId > 0) {
            $waterType = $this->waterTypeRepository->find($itemId);
        } else {
            $waterType = new Crc\Entity\WaterType();
        }

        //$form = new FormFactory\Form('WaterType', 'edit');

        $adapter = new CU_Form_Model_Adapter_Doctrine2($this->entityManager);
        $form = new CU_Form_Model(array(
            'adapter' => $adapter,
            'model' => 'Crc\Entity\WaterType'
        ));
        //$form->setRecord($watertype);

        /* //$waterTypes = new Application_Model_Collection_WaterType();
        $form = new Modules_Watertype_Forms_WaterType();
        $form->addSubForm($form, 'save');

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('save');
                $waterType->setFromArray($formData);
                $waterType->save();
                $this->_redirect('/watertype/admin/');
            }
        }
Zend_Debug::dump($waterType->toArray());
Zend_Debug::dump($waterType);
exit;
        $form->populate($waterType->toArray()); */
        $this->view->form = $form;
    }

    /**
     * Delete a user
     *
     * @return void
     */
    public function deleteAction()
    {
        $itemId = $this->getRequest()->getParam('id');
        $waterTypes = new Application_Model_Collection_WaterType();
        $waterType = $waterTypes->find($itemId)->current();
        $waterType->setStatus(Application_Model_WaterType::STATUS_DELETED)
                  ->save();
        $this->_redirect('/watertype/admin/');
    }
}